<template>
  <div>
    <!-- 信息查询表单 -->
    <Card class="formCard">
      <Form ref="form" :model="form" :rules="formRules">
        <Row gutter="40">
          <i-col span="6">
            <FormItem prop="organization">
              <Cascader change-on-select :data="organizationList" v-model="form.organization" placeholder="保单管理机构" clearable></Cascader>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="reagentOrganization">
              <Cascader change-on-select :data="organizationList" v-model="form.reagentOrganization" @on-change="organizationChange" placeholder="续期专员机构" clearable></Cascader>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="reagentName">
              <Select v-model="form.reagentName" placeholder="续期专员姓名" clearable multiple>
                <Option
                  v-for="item in reagentNameList"
                  :key="item.key"
                  :value="item.key"
                >{{item.value}}-{{item.key}}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="saleChannel">
              <Select v-model="form.saleChannel" placeholder="销售渠道" clearable>
                <Option
                  v-for="item in saleChannelList"
                  :key="item.key"
                  :value="item.key"
                >{{item.value}}</Option>
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <Row gutter="40">
          <i-col span="6">
            <FormItem prop="isWorkType">
              <Select v-model="form.isWorkType" placeholder="分单类型" clearable>
                <Option value="0">在职单</Option>
                <Option value="1">孤儿单</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="contno">
              <Input v-model="form.contno" placeholder="保单号" clearable />
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="signRange">
              <DatePicker
                type="daterange"
                placeholder="银行处理起始期"
                style="width:100%"
                v-model="form.signRange"
                :editable="false"
              ></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="deductResult">
              <Select v-model="form.deductResult" placeholder="扣款结果" clearable>
                <Option value="0">成功</Option>
                <Option value="1">失败</Option>
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col span="24">
            <Button type="primary" @click="handleSubmit()" :loading="queryLoading">查询</Button>
            <Button @click="handleReset()" class="queryButton">重置</Button>
            <Button type="primary" @click="downloadFile()" :disabled="queryState">导出</Button>
          </i-col>
        </Row>
      </Form>
    </Card>
    <!-- 表格信息显示 -->
    <Card class="tableCard">
      <Table
        :columns="transferColumns"
        :data="transferData"
        border
        @on-expand="tableOnExpand"
        :class="classShadow==false?'myTable':''"
      >
        <template slot-scope="{row}" slot="deductSuccessTime">
          <span v-if="row.deductResult == '成功'">{{row.deductSuccessTime}}</span>
          <span v-if="row.deductResult == '失败'">-</span>
        </template>
        <template v-if="transferData!=null" slot-scope="{row}" slot="contno">
          <span class="blue">{{row.contno}}</span>
        </template>
        <template slot-scope="{row}" slot="deductResult">
          <span v-if="row.deductResult == '成功'&& transferData!=null">
            <Button type="success" size="small" class="tableButton">成功</Button>
          </span>
          <span v-if="row.deductResult == '失败'&& transferData!=null">
            <Button type="error" size="small" class="tableButton">失败</Button>
          </span>
        </template>
      </Table>
      <Page
        :total="total"
        show-sizer
        show-total
        style="text-align:right;margin-top:20px"
        @on-change="pageChange"
        @on-page-size-change="pageSizeChange"
        :page-size-opts="pageSizeOptions"
        :current="pageIndex"
        :page-size="pageSize"
        transfer
      ></Page>
    </Card>
    <i-button @click="info" style="display:none"></i-button>
    <div class="contain" ref="mybox" v-show="false">
      <canvas id="myCanvas" width="200" height="100" ref="myCanvas" style="position: absolute;"></canvas>
    </div>
  </div>
</template>

<script>
import tableExpand from "./tableExpand";
import {drawSign} from '../../../util/drawSign';
import {exportFile} from "../../../util/util"
export default {
  components: {
    tableExpand: tableExpand
  },
  data() {
    const validateDaterange = (rule, value, callback) => {
      //console.log(value[1]);
      if (value[1] == "") {
        callback(new Error("银行处理起止期不能为空"));
      } else {
        callback();
      }
    };
    const validateOrganization = (rule, value, callback) => {
      //console.log(value[1]);
      if (!value) {
        callback(new Error("保单管理机构不能为空"));
      } else {
        callback();
      }
    };
    return {
      // 表单数据
      form: {
        organization: "",
        reagentOrganization: "",
        reagentName: [""],
        saleChannel: "",
        isWorkType: "",
        contno: "",
        signRange: ["", ""],
        deductResult: ""
      },
      organizationList: [],
      reagentOrganizationList: [],
      reagentNameList: [],
      saleChannelList: [],
      formRules: {
        organization: [
          { validator: validateOrganization, trigger: "blur" },
          { validator: validateOrganization, trigger: "change" }
        ],
        signRange: [
          { validator: validateDaterange, trigger: "blur" },
          { validator: validateDaterange, trigger: "change" }
        ]
      },
      // 表格数据
      transferColumns: [
        {
          type: "expand",
          width: "80",
          fixed: "left",
          render: (h, params) => {
            return h(tableExpand, {
              props: {
                row: params.row
              }
            });
          }
        },
        {
          title: "保单号",
          key: "contno",
          fixed: "left",
          width: 220,
          slot: "contno"
        },
        {
          title: "分单类型",
          key: "isWorkType",
          width: 140,
          align: "center"
        },
        {
          title: "投保人",
          key: "applicant",
          width: 140,
          align: "center"
        },
        {
          title: "应交日",
          key: "paytodate",
          align: "center",
          width: "160",
          // sortable: true
        },
        {
          title: "应交次数",
          key: "payyear",
          align: "center",
          width: "120"
        },
        {
          title: "应收保费(元)",
          key: "shouldPrem",
          align: "center",
          width: "160",
          // sortable: true
        },
        {
          title: "续期专员",
          key: "agent",
          align: "center",
          width: "220",
          // sortable: true
        },
        {
          title: "扣款成功时间",
          key: "deductSuccessTime",
          align: "center",
          width: "150",
          // sortable: true,
          slot: "deductSuccessTime"
        },
        {
          title: "是否首转",
          key: "isFirstTurn",
          align: "center",
          width: "130"
        },
        {
          title: "扣款结果",
          key: "deductResult",
          align: "center",
          minWidth: 150,
          fixed: "right",
          slot: "deductResult"
        }
      ],
      transferData: [],
      // 分页数据
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      pageSizeOptions: [5, 10, 15, 20],
      classShadow: true,
      expandSize: 0,
      pageObj: null,
      queryState: true,
      queryLoading: false
    };
  },
  methods: {
    // 工作统计下拉框信息
    getProfessionalList() {
      // this.api.professionalList().then(res => {
      //   if (res.code == 200 && res.data != null) {
      //     this.saleChannelList = res.data.salechnlListVOS;
      //     // 保单管理机构
      //     res.data.listKeyValueVOS.forEach(element => {
      //       this.organizationList.push(element);
      //     });
      //   } else {
      //     this.organizationList = [];
      //     this.saleChannelList = [];
      //   }
      //   //console.log(res);
      // });

      // 续期机构下拉框
      // this.api.selectUerList().then(res => {
      //   this.reagentOrganizationList = [];
      //   if (res.code == 200 && res.data != null) {
      //     this.reagentOrganizationList = res.data[0].listKeyValueVOS;
      //   } else {
      //     this.reagentOrganizationList = [];
      //   }
      // });
    },
    // 根据管理机构查询员工
    organizationChange(value) {
      // console.log(value);
      if (!value) {
        this.reagentNameList = [];
      } else {
        this.api.selectXQCode({ managecom: value[value.length-1] }).then(res => {
          if (res.code == 200) {
            if (res.data) {
              this.reagentNameList = res.data;
            } else {
              this.reagentNameList = [];
            }
            // console.log(res);
          } else {
            this.reagentNameList = [];
            this.$Message.info(res.msg);
          }
        });
      }
    },
    info(tip) {
      this.$Message.info(tip);
    },
    // 分页设置
    pageChange(pageIndex) {
      this.pageIndex = pageIndex;
      this.pageSubmit();
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageSubmit();
    },
    // 查询
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.queryLoading = true;
          this.transferData = [];
          let start =
            this.form.signRange[0].getFullYear() +
            "-" +
            String(this.form.signRange[0].getMonth() + 1) +
            "-" +
            this.form.signRange[0].getDate();
          let end =
            this.form.signRange[1].getFullYear() +
            "-" +
            String(this.form.signRange[1].getMonth() + 1) +
            "-" +
            this.form.signRange[1].getDate();

          let obj = {
            batchtype: this.form.isWorkType,
            contno: this.form.contno,
            dealbegintime: start,
            dealendtime: end,
            index: this.pageIndex,
            managecom: this.form.organization[this.form.organization.length-1],
            pageSize: this.pageSize,
            reagentcode: this.form.reagentName + "",
            remanagecom: this.form.reagentOrganization[this.form.reagentOrganization.length-1],
            result: this.form.deductResult,
            salechnl: this.form.saleChannel
          };

          for (let item in obj) {
            if (obj[item] == null || obj[item].length == 0) {
              delete obj[item];
            }
          }
          // console.log(obj);
          this.pageObj = obj;
          this.transferData = [];
          this.total = 0;
          this.api.doTransferAccounts(obj).then(res => {
            if (res.code == 200 && res.data != null) {
              if (res.data.total > 0) {
                res.data.records.forEach(element => {
                  let list = {
                    contno: "",
                    isWorkType: "",
                    applicant: "",
                    paytodate: "",
                    payyear: "",
                    shouldPrem: "",
                    agent: "",
                    deductSuccessTime: "",
                    isFirstTurn: "",
                    deductResult: ""
                  };
                  list.contno = element.contno;
                  list.isWorkType = element.conttype;
                  list.applicant = element.appntname;
                  list.paytodate = element.paydate;
                  list.payyear = element.paytime + "年交";
                  list.shouldPrem = element.dueprem;
                  list.agent = element.renewalname + "-" + element.renewalno;
                  list.deductSuccessTime = element.dealdate;
                  list.isFirstTurn = element.firsttutn;
                  list.deductResult = element.dealresult;

                  this.transferData.push(list);
                  //console.log(list)
                });
                // console.log(this.transferData)
                this.total = res.data.total;
                this.queryState = false;
                this.queryLoading = false;
                this.info(res.msg);
              } else {
                this.transferData = [];
                this.total = 0;
                this.queryState = true;
                this.queryLoading = false;
                this.info("暂无数据");
              }
            } else {
              this.queryLoading = false;
              this.total = 0;
              this.transferData = [];
              this.info(res.msg);
              this.queryState = true;
            }
            // console.log(this.transferData);
          });
        }
      });
    },
    // 分页查询
    pageSubmit() {
      this.pageObj.index = this.pageIndex;
      this.pageObj.pageSize = this.pageSize;

      this.api.doTransferAccounts(this.pageObj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.transferData = [];
          res.data.records.forEach(element => {
            let list = {
              contno: "",
              isWorkType: "",
              applicant: "",
              paytodate: "",
              payyear: "",
              shouldPrem: "",
              agent: "",
              deductSuccessTime: "",
              isFirstTurn: "",
              deductResult: ""
            };
            list.contno = element.contno;
            list.isWorkType = element.conttype;
            list.applicant = element.appntname;
            list.paytodate = element.paydate;
            list.payyear = element.paytime + "年交";
            list.shouldPrem = element.dueprem;
            list.agent = element.renewalname + "-" + element.renewalno;
            list.deductSuccessTime = element.dealdate;
            list.isFirstTurn = element.firsttutn;
            list.deductResult = element.dealresult;

            this.transferData.push(list);
            //console.log(list)
          });
          //console.log(this.transferData)
        }
      });
    },
    handleReset() {
      this.queryLoading = false;
      this.$refs.form.resetFields();
    },
    tableOnExpand(row, status) {
      if (status == true) {
        this.expandSize++;
      }
      if (status == false) {
        this.expandSize--;
      }
      if (this.expandSize == 0) {
        this.classShadow = true;
      } else {
        this.classShadow = false;
      }
    },
    // 转账清单导出Excel
    downloadFile() {
      // let url = "../rest/export/getTransferAccountsExcel";
      // console.log(this.pageObj);
      this.pageObj.batchtype = this.pageObj.batchtype?this.pageObj.batchtype:'';
      this.pageObj.contno = this.pageObj.contno?this.pageObj.contno:'';
      this.pageObj.reagentcode = this.pageObj.reagentcode?this.pageObj.reagentcode:'';
      this.pageObj.remanagecom = this.pageObj.remanagecom?this.pageObj.remanagecom:'';
      this.pageObj.salechnl = this.pageObj.salechnl?this.pageObj.salechnl:'';
      this.pageObj.result = this.pageObj.result?this.pageObj.result:'';
      let newreagentCode = this.pageObj.reagentcode?this.pageObj.reagentcode.split(','):[]
      let obj ={
        batchtype:this.pageObj.batchtype,
        contno:this.pageObj.contno,
        dealbegintime:this.pageObj.dealbegintime,
        dealendtime:this.pageObj.dealendtime,
        managecom:this.pageObj.managecom,
        reagentcode:newreagentCode||[],
        remanagecom:this.pageObj.remanagecom,
        result:this.pageObj.result,
        salechnl:this.pageObj.salechnl,
      }
      exportFile("scrm-gateway/scrm-uer/api/export/getTransferAccountsExcel",obj)
      // window.open(
      //   url +
      //     "?batchtype=" +
      //     this.pageObj.batchtype +
      //     "&contno=" +
      //     this.pageObj.contno +
      //     "&dealbegintime=" +
      //     this.pageObj.dealbegintime +
      //     "&dealendtime=" +
      //     this.pageObj.dealendtime +
      //     "&managecom=" +
      //     this.pageObj.managecom +
      //     "&reagentcode=" +
      //     this.pageObj.reagentcode +
      //     "&remanagecom=" +
      //     this.pageObj.remanagecom +
      //     "&result=" +
      //     this.pageObj.result +
      //     "&salechnl=" +
      //     this.pageObj.salechnl
      // );
    },
    draw(ele,loginUser,loginTime) {
      let imageUrl = drawSign(ele,loginUser,loginTime)
      document.getElementsByClassName("ivu-table-fixed-body")[0].style.background = 'url(' + imageUrl + ') left top repeat'
      document.getElementsByClassName("ivu-table-fixed-body")[0].classList.add("add-background")
      document.getElementsByClassName("ivu-table-fixed-body")[1].style.background = 'url(' + imageUrl + ') left top repeat'
      document.getElementsByClassName("ivu-table-fixed-body")[1].classList.add("add-background")
      document.getElementsByClassName("ivu-table-body")[0].style.background = 'url(' + imageUrl + ') left top repeat'
      document.getElementsByClassName("ivu-table-body")[0].classList.add("add-background")
    },
    getOrganization(){
      this.api.remanagecomList().then(res => {
        if (res.code == 200 && res.data != null) {
          let arr = []
          arr.push(res.data)
          arr.forEach(one=>{
            one.value = one.comcode
            one.label = one.comcode + '-' + one.name
            one.children = one.chilDren || []
            if (one.children) {
              one.chilDren.forEach(two=>{
                two.value = two.comcode
                two.label = two.comcode + '-' + two.name
                two.children = two.chilDren || []
                if (two.children) {
                  two.children.forEach(three=>{
                    three.value = three.comcode
                    three.label = three.comcode + '-' + three.name
                    three.children = three.chilDren || []
                    if (three.children) {
                      three.children.forEach(four=>{
                        four.value = four.comcode
                        four.label = four.comcode + '-' + four.name
                        four.children = four.chilDren || []
                      })
                    }
                  })
                }
              })
            }
          })
          console.log(arr);
          this.organizationList = arr
        } else {
          this.organizationList = [];
        }
      });
    }
  },
  mounted() {
    this.getOrganization()
    this.getProfessionalList();
    let loginUser = sessionStorage.getItem("name");
    let loginTime =
    new Date().getFullYear() +
    "/" +
    (new Date().getMonth() + 1) +
    "/" +
    (new Date().getDate());
    this.draw(this.$refs.myCanvas,loginUser,loginTime)
  }
};
</script>
<style scoped lang="less">
@import "./index";
</style>

<style lang="less">
@import "./index";
.myTable .ivu-table-fixed {
  box-shadow: none;
}
.myTable .ivu-table-fixed-right {
  box-shadow: none;
}
.myTable .ivu-table-fixed {
  left: 1px;
}
.myTable td.ivu-table-expanded-cell {
  background: #fff;
}
.add-background td{
  background-color: rgba(255,255,255,0) !important;
  background: rgba(255,255,255,0) !important;
}
.myTable td.ivu-table-expanded-cell {
    position: relative;
    z-index: 9999;
}
</style>
